package actualizador.datagramExample;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class DatagramaEjemplo {
	public static final int PUERTO= 1500, MAX_LEN = 512, DEFAULT_TIMEOUT= 2500;
	public static final String BROADCAST= "255.255.255.255";
	private DatagramSocket socket;

	public void enviarMensajeBroadcast(String mensaje) throws UnknownHostException, SocketException, IOException{
		this.enviar(BROADCAST, mensaje, true);
	}

	public void enviarMensaje(String ipDestino, String mensaje) throws UnknownHostException, SocketException, IOException{
		this.enviar(ipDestino, mensaje, false);
	}

	private void enviar(String ipDestino, String mensaje, boolean modoBroadcast) throws UnknownHostException, SocketException, IOException{
		InetAddress hostReceptor = InetAddress.getByName(ipDestino);
		// instanciar un datagramSocket para enviar datos
		socket = new DatagramSocket();
		socket.setBroadcast(modoBroadcast);
		byte[] buffer = mensaje.getBytes();
		DatagramPacket datagram = new DatagramPacket(buffer, buffer.length,
				hostReceptor, PUERTO);
		socket.send(datagram);
		socket.close();
	}

	public String recibirMensaje(int timeout) throws UnknownHostException, SocketException, IOException{
		return this.recibir(timeout);
	}
	
	public String recibirMensaje() throws UnknownHostException, SocketException, IOException{
		return this.recibir(DEFAULT_TIMEOUT);
	}
	
	private String recibir(int timeout) throws UnknownHostException, SocketException, IOException{
		socket = new DatagramSocket(PUERTO);
		socket.setSoTimeout(timeout);
		// instanciar un datagramSocket para recibir datos
		byte[] buffer = new byte[MAX_LEN];
		DatagramPacket datagram = new DatagramPacket(buffer, MAX_LEN);
		socket.receive(datagram);
		String mensaje = new String(buffer);
		socket.close();
		return mensaje;
	}
	
	public void cerrarDatagrama(){
		if(!socket.isClosed())
			socket.close();
	}
}
